//
//  OAMyMessageViewController.m
//  ERP
//
//  Created by goldeney on 15/1/19.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OAMyMessageViewController.h"
#import "MJRefresh.h"
#import "OAMyMessageViewCell.h"
#import "UITableView+Custom.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"
#import "ServiceConnect.h"

#import "OAMessageDetailViewController.h"

@interface OAMyMessageViewController ()

@property (strong, nonatomic) NSMutableArray *resultData;
@property (strong, nonatomic) NSMutableArray *searchData;

@property (assign, nonatomic) NSInteger segmentActionState;

@property (strong, nonatomic) UIView *searchMainView;
@property (strong, nonatomic) UITableView *searchTableView;

@end

@implementation OAMyMessageViewController
@synthesize segmentedView = _segmentedView;
@synthesize tableView = _tableView;
@synthesize searchMainView = _searchMainView;
@synthesize searchTableView = _searchTableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"企业通知"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    self.segmentActionState = 2;//所有消息
    [self.segmentedView setTintColor:ThemeColorBlue];
    [self.segmentedView addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self setupRefresh];
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

//具体委托方法实例
-(void)segmentAction:(UISegmentedControl *)Seg
{
    //查询类型 0.收到消息未读，1.收到消息已读 2.所有消息
    NSInteger index = Seg.selectedSegmentIndex;
    if (index == 0) self.segmentActionState = 2;//所有消息
    else if (index == 1) self.segmentActionState = 0;//消息未读
    else if (index == 2) self.segmentActionState = 1;//消息已读
    
    [self.resultData removeAllObjects];
    [self.tableView reloadData];
    [self.tableView headerBeginRefreshing];
}


#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    
    //查询类型 0.收到消息未读，1.收到消息已读 2.所有消息
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userInfo.Id forKey:@"userid"];
    [model setValue:[NSNumber numberWithInteger:self.segmentActionState] forKey:@"type"];
    [model setValue:state forKey:@"between"];
    [model setValue:end forKey:@"and"];
    [model setValue:@"" forKey:@"searchVal"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_getMsgReceive" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        //添加数据，刷新页面
        if(result.resultArray && result.resultArray.count>0){
            NSMutableArray *newArray = [NSMutableArray array];
            for (NSDictionary *dic in result.resultArray)
                [newArray addObject:[NSMutableDictionary dictionaryWithDictionary:dic]];
            
            if(isReresh) [self.resultData removeAllObjects];
            [self.resultData addObjectsFromArray:newArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无消息" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:1];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count +1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return @"";
    } else {
        return @" 消息搜索结果";
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"OAMyMessageViewCell";
    OAMyMessageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[OAMyMessageViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
    
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    cell.typeLable.text = [model objectFormatStringForKey:@"functionname"];
    cell.peopleLable.text = [model objectFormatStringForKey:@"username"];
    cell.timeLable.text = [model objectFormatStringForKey:@"creationtime"];
    
    //是否阅读标记
    NSInteger isRead = [[model objectFormatForKey:@"isred"] integerValue];
    if(isRead > 0){
        cell.badgeImageView.hidden = YES;
        cell.titleLable.text = [model objectFormatStringForKey:@"msgcontent"];
    } else {
        NSString *title = [model objectFormatStringForKey:@"msgcontent"];
        cell.badgeImageView.hidden = NO;
        cell.titleLable.text = [NSString stringWithFormat:@"        %@",title];
    }
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    NSInteger isred = [[model objectFormatForKey:@"isred"] integerValue];
    if (isred <= 0) { //提交已读
        [self submitMessageInfoId:[model objectFormatForKey:@"id"] model:model];
    }
    
    OAMessageDetailViewController *viewController = [[OAMessageDetailViewController alloc] initWithValue:@[@0,model]];
    [self.navigationController pushViewController:viewController animated:YES];
}


#pragma mark - 已读提交

- (void)submitMessageInfoId:(NSString*)msgid model:(NSMutableDictionary *)value
{
    //提交已读 1、消息 2、公文
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:msgid forKey:@"msgid"];
    [model setValue:userInfo.Id forKey:@"userid"];
    [model setValue:@1 forKey:@"type"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_MsgRead" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if (result.resultArray && result.resultArray.count>0) {
            NSDictionary *resultArray = [result.resultArray firstObject];
            NSInteger resultState = [[resultArray objectFormatForKey:@"result"] integerValue];
            if (resultState == 1){
                [value setObject:[NSNumber numberWithInteger:1] forKey:@"isred"];
                [self.tableView reloadData];
            }
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===submitMessageInfoId==%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"==submitMessageInfoId===%@",error);
    }];
}

@end
